package com.superb.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.superb.entity.Blog;
import com.superb.service.BlogService;
//import com.superb.shiro.AccountProfile;
import com.superb.util.Result;
//import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author anonymous
 * @since 2020-11-08
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;

    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") int currentPage){
        Page<Blog> page = new Page<>(currentPage,5);
        IPage<Blog> pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        return Result.success(pageData);
    }

    @GetMapping("/list/{blogId}")
    public Result list(@PathVariable(name = "blogId") long id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"该博客不存在");
        return Result.success(blog);
    }


    //添加或编辑
//    @RequiresAuthentication
    @PostMapping("/edit")
    public Result list(@Validated @RequestBody Blog blog){
        //添加
        if (blog.getId() == null){
            blog.setCreated(LocalDateTime.now());
            blog.setStatus(0);
        }


//        BeanUtil.copyProperties(blog,temp,"id","created","status");


        blogService.saveOrUpdate(blog);


        return Result.success(blog);
    }

    //删除
    @PostMapping("/remove")
    public Result delete(@Validated @RequestBody Blog blog){
        if (blog != null){
            blogService.removeById(blog.getId());
            return Result.success("删除成功",null);
        }
        return Result.fail();
    }
}
